import React, { Fragment } from "react";
import { addAttachment, backUserTasks, delAttachment, executeTask, nextNodeVariables } from "../props/service";
import { Button, Descriptions, message } from "antd";
import {
    ModalForm, ProFormDependency, ProFormGroup, ProFormInstance, ProFormItem, ProFormList,
    ProFormRadio, ProFormSelect, ProFormText, ProFormTextArea, ProFormUploadButton, ProTable
} from "@ant-design/pro-components";
import { ActionType } from 'easy-flowable-react/dist/Bpmn/props/panel';
import { useModel } from "@umijs/max";

interface EasyExecuteProps {
    /**
     * @description 流程状态
     */
    status: boolean;
    /**
     * @description 流程实例ID
     */
    processInstanceId: string;
    /**
     * @description 任务ID
     */
    taskId: string;
    /**
     * @description 表格刷新
     */
    reload: () => void;
    /**
     * @description 是否为link
     */
    link?: boolean;
}

export default (props: EasyExecuteProps) => {

    const { initialState } = useModel('@@initialState');
    const { users } = initialState;
    const actionFormRef = React.useRef<ProFormInstance>();
    const [actions, setActions] = React.useState();

    return <ModalForm
        modalProps={{
            mask: false,
            maskClosable: false,
            destroyOnClose: true,
            onCancel: async () => {
                const attachmentId = actionFormRef.current?.getFieldValue('attachmentId');
                if (attachmentId) {
                    await delAttachment(attachmentId[0].response.result);
                }
            }
        }}
        formRef={actionFormRef}
        title="流程审批"
        layout="horizontal"
        labelCol={{ span: 3 }}
        trigger={<Button type={props.link ? "link" : "primary"} disabled={props.status || !props.taskId}>执行</Button>}
        request={async () => {
            const data: any = { flowCommentType: 'AGREE' };
            const { success, result } = await nextNodeVariables(props.taskId);
            if (success && result) {
                if (result.sequenceFlow.length) {
                    data.nodes = result.sequenceFlow;
                }
                if (result.attributes.actions) {
                    setActions(ActionType.filter(i => result.attributes?.actions.some(item => item === i.value)));
                }
            }
            return data;
        }}
        onFinish={async (values) => {
            let attachmentId, commentContent = values.commentContent;
            if (values.attachmentId) {
                const file = values.attachmentId[0];
                commentContent = JSON.stringify({
                    message: values.commentContent,
                    filename: file.name
                });
                attachmentId = file.response.result;
            }
            const variables: any = {};
            if (values.variables && values.variables.length) {
                values.variables.forEach(item => {
                    variables[item.key] = item.value;
                });
            }
            const { success } = await executeTask({
                ...values, commentContent, attachmentId,
                processInstanceId: props.processInstanceId,
                taskId: props.taskId, variables
            });
            if (success) {
                message.success('执行成功！');
                props.reload();
            }
            return success;
        }}>
        <ProFormRadio.Group name="flowCommentType" label="操作" options={actions || ActionType} rules={[{ required: true, message: '执行操作不能为空' }]}/>
        <ProFormDependency name={['flowCommentType']}>
            {({flowCommentType}) => {
                if (flowCommentType == 'REJECT_TO_TASK') {
                    return <ProFormItem name="rejectToTaskId" label="节点" rules={[{ required: true, message: '驳回节点不能为空' }]}>
                        <ProTable
                            request={async () => {
                                const { success, result } = await backUserTasks(props.processInstanceId);
                                return {
                                    success,
                                    data: result || []
                                }
                            }}
                            search={false}
                            options={false}
                            pagination={false}
                            rowKey="value"
                            rowHoverable={false}
                            tableAlertRender={false}
                            rowSelection={{
                                type: 'radio',
                                columnTitle: '选择',
                                columnWidth: 80,
                                onSelect: ({ value }) => {
                                    actionFormRef.current?.setFieldValue('rejectToTaskId', value);
                                }
                            }}
                            columns={[
                                { title: '节点名称', dataIndex: 'label' },
                                { title: '节点key', dataIndex: 'value' },
                            ]}/>
                    </ProFormItem>
                } else if (flowCommentType == 'DELEGATE' || flowCommentType == 'ASSIGN') {
                    return <ProFormSelect name="userId" rules={[{ required: true, message: '执行人不能为空' }]} label="执行人" request={() => users}/>
                }
            }}
        </ProFormDependency>
        <ProFormTextArea label="审批意见" rules={[{ required: true, message: '审批意见不能为空' }]} name="commentContent"/>
        <ProFormDependency name={['nodes', 'flowCommentType']}>
            {({ nodes, flowCommentType }) => {
                if (nodes && nodes.length && flowCommentType === 'AGREE') {
                    return <>
                        <ProFormItem label="目标节点">
                            <Descriptions bordered size="small" style={{ width: '100%' }} column={2}>
                                { nodes.map((i, index) => <Fragment key={'nodes_' + index}>
                                    <Descriptions.Item label="目标节点">{i.label}</Descriptions.Item>
                                    <Descriptions.Item label="表达式">{i.value}</Descriptions.Item>
                                </Fragment>) }
                            </Descriptions>
                        </ProFormItem>
                        <ProFormList name="variables" label="流程变量" creatorButtonProps={{ creatorButtonText: '添加流程变量' }}>
                            <ProFormGroup>
                                <ProFormText label="key" name="key" rules={[{ required: true, message: '流程变量key不能为空' }]} />
                                <ProFormText label="value" name="value" rules={[{ required: true, message: '流程变量value不能为空' }]} />
                            </ProFormGroup>
                        </ProFormList>
                    </>
                }
            }}
        </ProFormDependency>
        <ProFormUploadButton
            name="attachmentId"
            fieldProps={{
                onRemove: async (file) => {
                    const { success } = await delAttachment(file.response.result);
                    return success;
                }
            }}
            label="附件" max={1}
            action={addAttachment(props.taskId, props.processInstanceId)} />
    </ModalForm>
}